package cn.tedu.apps_system.service.impl;

import cn.tedu.apps_system.base.response.JsonResult;
import cn.tedu.apps_system.base.response.ResultCode;
import cn.tedu.apps_system.exception.BusinessException;
import cn.tedu.apps_system.mapper.OrderItemMapper;
import cn.tedu.apps_system.mapper.OrderMapper;
import cn.tedu.apps_system.pojo.dto.OrderCreateRequestDto;
import cn.tedu.apps_system.pojo.dto.OrderReviseDto;
import cn.tedu.apps_system.pojo.entity.Order;
import cn.tedu.apps_system.pojo.entity.OrderItem;
import cn.tedu.apps_system.pojo.vo.OrderItemVO;
import cn.tedu.apps_system.pojo.vo.OrderVO;
import cn.tedu.apps_system.pojo.vo.UserVO;
import cn.tedu.apps_system.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public JsonResult createOrder(OrderCreateRequestDto request, HttpSession session) {
        log.debug("OrderItemDto :"+request);
        UserVO userVO = (UserVO) session.getAttribute("user");
//        if (userVO == null) {
//            return new JsonResult(ResultCode.UNAUTHORIZED);
//        }

        // 1. 生成唯一订单号（示例：时间戳+用户ID+随机数）
        String orderNo = String.format("ORDER_%d_%d_%04d", userVO.getId(), System.currentTimeMillis(), new Random().nextInt(10000));




        /*// 2. 计算商品总价
        double itemTotal = request.getItems().stream()
                .mapToDouble(item -> item.getPrice().doubleValue() * item.getQuantity())
                .sum();

        // 3. 计算订单总金额（商品总价 + 运费）
        double totalAmount = itemTotal + request.getFreight();

        // 4. 构建订单对象
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(request.getUserId());
        order.setMerchantId(request.getMerchantId());
        order.setTotalAmount(totalAmount);
        order.setActualAmount(totalAmount); // 假设无优惠
        order.setFreight(request.getFreight());
        order.setStatus(0);
        order.setShippingAddress(request.getShippingAddress());
        order.setContactPhone(request.getContactPhone());
        order.setContactName(request.getContactName());
        order.setRemark(request.getRemark());
        order.setPaymentType(request.getPaymentType());
        order.setPaymentTime(new Date());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        int n = orderMapper.create(order);*/
        /*// 5. 添加订单商品明细
        List<OrderItem> items = request.getItems().stream()
                .map(item -> {
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrderId(order.getId());
                    orderItem.setProductId(item.getProductId());
                    orderItem.setProductName(item.getProductName());
                    orderItem.setProductImage(item.getProductImage());
                    orderItem.setPrice(item.getPrice());
                    orderItem.setQuantity(item.getQuantity());
                    orderItem.setTotalPrice(item.getPrice().doubleValue()*item.getQuantity());
                    orderItem.setCreateTime(new Date());
                    return orderItem;
                }).collect(Collectors.toList());

        int m=0;
        for (OrderItem orderItem : items) {
            m = orderMapper.addItems(Collections.singletonList(orderItem));
        }

        if (n>0 && m>0) {
            return JsonResult.ok(orderNo);
        }*/
        return new JsonResult(ResultCode.FAILED);
    }

    @Override
    public JsonResult reviseOrder(OrderReviseDto orderReviseDto, HttpSession session) {
        log.debug("OrderReviseDto: "+orderReviseDto);
        //UserVO userVO = (UserVO) session.getAttribute("user");
        Order order = new Order();
        BeanUtils.copyProperties(orderReviseDto,order);
        order.setUpdateTime(new Date());

        int n = orderMapper.reviseOrder(order);
        if(n>0){
            return JsonResult.ok();
        }
        return new JsonResult(ResultCode.FAILED);
    }

    @Override
    public JsonResult delete(OrderReviseDto orderReviseDto, HttpSession session) {
        log.debug("OrderReviseDto: "+orderReviseDto);
        //UserVO userVO = (UserVO) session.getAttribute("user");

        int n = orderMapper.deleteOrder(orderReviseDto);
        if(n>0){
            return JsonResult.ok();
        }
        return new JsonResult(ResultCode.FAILED);
    }

    @Override
    public JsonResult select(OrderReviseDto orderReviseDto, HttpSession session) {
        log.debug("OrderReviseDto: "+orderReviseDto);
        //UserVO userVO = (UserVO) session.getAttribute("user");

        OrderVO orderVO = orderMapper.selectOrder(orderReviseDto);
        if (orderVO == null) {
            return new JsonResult(ResultCode.SUCCESS,orderVO);
        }
        return new JsonResult(ResultCode.FAILED);
    }

    @Override
    public JsonResult selectAll(OrderReviseDto orderReviseDto, HttpSession session) {
        log.debug("OrderReviseDto: "+orderReviseDto);

        OrderVO orderVO = orderMapper.selectAllOrder(orderReviseDto);
        if (orderVO == null) {
            return new JsonResult(ResultCode.FAILED);
        }
        return JsonResult.ok(orderVO);
    }
    //商家修改添加


    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public OrderVO getById(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException(ResultCode.ORDER_NOT_EXIST);
        }

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);

        // 获取订单项
        List<OrderItem> orderItems = orderItemMapper.selectByOrderId(id);
        List<OrderItemVO> orderItemVOs = orderItems.stream().map(item -> {
            OrderItemVO orderItemVO = new OrderItemVO();
            BeanUtils.copyProperties(item, orderItemVO);
            return orderItemVO;
        }).collect(Collectors.toList());

        orderVO.setItems(orderItemVOs);
        return orderVO;
    }

    @Override
    public List<OrderVO> listByMerchantId(Long merchantId) {
        List<Order> orders = orderMapper.selectByMerchantId(merchantId);
        return orders.stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            return orderVO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<OrderVO> listByMerchantIdAndStatus(Long merchantId, Integer status) {
        List<Order> orders = orderMapper.selectByMerchantIdAndStatus(merchantId, status);
        return orders.stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            return orderVO;
        }).collect(Collectors.toList());
    }

    @Override
    public void delete(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException(ResultCode.ORDER_NOT_EXIST);
        }

        // 只有已完成或已取消的订单才能删除
        if (order.getStatus() != 3 && order.getStatus() != 4) {
            throw new BusinessException(ResultCode.ORDER_STATUS_ERROR);
        }

        orderMapper.deleteById(id);
    }
}

